package com.fingard.dsp.bank.directbank.sdebank01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.directbank.cmbc01.CMBC01Receipt;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.net.ConnState;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.sql.Connection;
import java.util.Date;
import java.util.Map;
import java.util.UUID;
/**
 * @author: liuxb
 * @create: 2019-12-02 14:32
 * @version: 1.0
 **/
public class SDEBANK01SinglePay extends SDEBANK01Base implements ISinglePay {
    @Override
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        synchronized (SDEBANK01SinglePay.class) {
            // 返回给ATS的对象
            RetAtsSingle retAtsSingle = new RetAtsSingle(p_req1908.reqHeader);
            RetAtsSglDetail detail = new RetAtsSglDetail();//用于提取银行返回报文信息的对象
            try {
                //赋值通用参数
                SDEBANK01Header header = new SDEBANK01Header();
                SDEBANK01Base base = new SDEBANK01Base();
                header.ERPJnlNo = base.getTrmSeqNum();// 凭证号,即ERP（财务系统）交易流水号
                header.ERPTrsTimestamp = p_req1908.reqHeader.transTime;//指令请求时间
                header.TrsCode = "B2ECrossBankTransfer";//交易码（无法区分行内、跨行转账，直接使用汇兑交易码）
                //拼接请求报文头
                XmlTextWriter xmlTextWriter = new XmlTextWriter();
                writeCommonHeader(xmlTextWriter, header);
                //拼接请求报文体
                xmlTextWriter.writeStartElement("Body");
                xmlTextWriter.writeElementString("SubmitNo", header.ERPJnlNo);//凭证号,即ERP（财务系统）交易流水号
                xmlTextWriter.writeStartElement("List");
                XElement tmpXElement = new XElement("Map", "");
                tmpXElement.addChild(new XElement("PayerAcNo", p_req1908.singleDetail.payAct));//转出账号
                tmpXElement.addChild(new XElement("PayerAcName", p_req1908.singleDetail.payName));//转出帐号户名
                tmpXElement.addChild(new XElement("TrsPassword", "888888"));//账户支取密码
//            tmpXElement.addChild(new XElement("Currency", p_req1908.singleDetail.payCur));//币种代码
                tmpXElement.addChild(new XElement("Currency", convertCurToBank(p_req1908.singleDetail.payCur)));//付方币种
                tmpXElement.addChild(new XElement("Amount", p_req1908.singleDetail.payAmount));//金额
                tmpXElement.addChild(new XElement("PayeeAcNo", p_req1908.singleDetail.recAct));//转入账号
                tmpXElement.addChild(new XElement("PayeeAcName", p_req1908.singleDetail.recName));//转入户名
                tmpXElement.addChild(new XElement("PayeeBankId", p_req1908.singleDetail.cnapsCode));//接收行行号
                tmpXElement.addChild(new XElement("PayeeBankName", p_req1908.singleDetail.cnapsName));//接收行行名
                tmpXElement.addChild(new XElement("UnionDeptId", p_req1908.singleDetail.cnapsCode));//接收网点号（接收行行号）
                tmpXElement.addChild(new XElement("Remark", p_req1908.singleDetail.purpose));//用途
                tmpXElement.addChild(new XElement("TransferType", "0"));//汇款类型 0－普通汇款，目前固定送0即可
                tmpXElement.addChild(new XElement("Priority", "Y"));//加急标志 Y-加急，对于普通汇款，走大额(目前只支持标志Y)
                nodeAnalysis(p_req1908.singleDetail.srcXElement, tmpXElement, getCharset());//分析报文节点
                xmlTextWriter.writeXElement(tmpXElement);
                xmlTextWriter.writeEndDocument();

                // 发送报文到银行
                String[] bankResult = sendToBank(xmlTextWriter.toXmlString(), header);
                Thread.sleep(this.getBankConfig().getValueAsInt("waitTimeForReq"),5000);

//            //模拟银行返回
//            String s = "<Message>\n" +
//                    "\t<Head>\n" +
//                    "\t\t\t<IBSReturnCode>000000</IBSReturnCode>\n" +
//                    "\t\t\t<IBSReturnMsg>银企交易成功！</IBSReturnMsg>\n" +
//                    "\t</Head>\n" +
//                    "\t<Body>\n" +
//                    "\t\t<List>\n" +
//                    "\t\t\t<Map>\n" +
//                    "\t\t\t\t<ReturnCode>000000</ReturnCode>\n" +
//                    "\t\t\t\t<ReturnMsg>成功！</ReturnMsg>\n" +
//                    "\t\t\t\t<PayerBalance>15000.88</PayerBalance>\n" +
//                    "\t\t\t</Map>\n" +
//                    "\t\t</List>\n" +
//                    "</Body>\n" +
//                    "</Message>\n";
//            String[] bankResult = new String[]{"", s};

                if (bankResult[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();// 接收提示信息
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSbMsg);
                    if (tmpBkReader != null) {// 返回内容不为空
                        String IBSReturnCode = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                        String IBSJnlNo = tmpBkReader.getFirstText("/Message/Head/IBSReturnMsg");
                        if ("000000".equals(IBSReturnCode)) {
                            //记录ats支付流水号对应的银行指令流水号，供查询状态接口使用
                            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                            Connection conn = FGBiz.getLocalDbConn();//取本地文件数据库连接
                            //批号
                            JDBCHelper.update(conn, INSERTSEQONE, new Object[]{uuid, p_req1908.reqHeader.bankCode, Format.Date8Format.format(new Date()), p_req1908.reqHeader.reqSeqID, header.ERPJnlNo});
                            String returnCode = tmpBkReader.getFirstText("/Message/Body/List/Map/ReturnCode");
                            String returnMsg = tmpBkReader.getFirstText("/Message/Body/List/Map/ReturnMsg");
                            detail.respCode = "0";
                            detail.respInfo = returnMsg;
                            detail.reqSeqID = p_req1908.singleDetail.askNumber;// 交易流水号
                            detail.transState = returnCode;
                            detail.payInfoCode = detail.transState;
//                        detail.transAmt = tmpBkReader.getFirstText("/Message/Body/List/Map/PayerBalance");//转出帐号余额
                        } else {
                            detail.respCode = "-1";
                            detail.respInfo = IBSJnlNo;
                        }
                    } else {
                        detail.respCode = "-1";
                        detail.respInfo = tmpSbMsg.toString();
                    }
                } else if (bankResult[0].equals(ConnState.FAIL)) {
                    detail.respCode = "0";
                    detail.respInfo = bankResult[1];
                    detail.reqSeqID = p_req1908.singleDetail.askNumber;
                    detail.transState = PaymentState.FAIL_Payment;
                    detail.payInfoCode = bankResult[0];
                } else {
                    detail.respCode = "-1";
                    detail.respInfo = bankResult[1];
                    detail.reqSeqID = p_req1908.singleDetail.askNumber;
                }


            } catch (Exception ex) {
                detail.respCode = "-1";
                detail.respInfo = ex.getMessage();
                ex.printStackTrace();
            }
            retAtsSingle.writeRetDetail(detail);
            retAtsSingle.writeEnd();
            return retAtsSingle;
        }
    }

    @Override
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        RetAtsSingle retAtsSingle = new RetAtsSingle(p_req1944.reqHeader);
        RetAtsSglDetail detail = new RetAtsSglDetail();
        try {
            XmlTextWriter xmlTextWriter = new XmlTextWriter();
            SDEBANK01Header header = new SDEBANK01Header();
            header.TrsCode = "B2ETrsResultQryV1";
            header.ERPJnlNo = p_req1944.reqHeader.transSeqID;

            //拼接请求报文头
            writeCommonHeader(xmlTextWriter, header);
            //拼接请求报文体
            xmlTextWriter.writeStartElement("Body");
            xmlTextWriter.writeStartElement("List");
//            XElement tmpXElement = new XElement("Map","");
            xmlTextWriter.writeStartElement("Map");
            xmlTextWriter.writeElementString("AcNo", p_req1944.payAct);//付款帐号
            Connection conn = FGBiz.getLocalDbConn();
            Map<String, Object> selMap = JDBCHelper.execQuerySingle(conn, SELECTSEQONE, new Object[]{p_req1944.reqHeader.reqSeqID, p_req1944.reqHeader.bankCode});
            if (selMap.size() > 0) {
                p_req1944.reqHeader.transSeqID = selMap.get("BANKREQSEQID").toString();
                xmlTextWriter.writeElementString("VoucherJnlNo", p_req1944.reqHeader.transSeqID);//凭证号,即交易流水号
            } else {
                retAtsSingle.writeRespCode("-1");
                retAtsSingle.writeRespInfo("交易流水号关联映射异常，请检查");
                return retAtsSingle;
            }
            xmlTextWriter.writeEndDocument();

            // 发送报文到银行
            String[] bankResult = sendToBank(xmlTextWriter.toXmlString(), header);

            //模拟银行返回
//            String s = "<Message>\n" +
//                    "\t<Head>\n" +
//                    "\t\t\t<IBSReturnCode>000000</IBSReturnCode>\n" +
//                    "\t\t\t<IBSReturnMsg>银企交易成功！</IBSReturnMsg>\n" +
//                    "\t</Head>\n" +
//                    "<Body>\n" +
//                    "\t\t <List>\n" +
//                    "\t\t\t\t<Map>\n" +
//                    "\t\t\t\t\t<ReturnCode>000000</ReturnCode>\n" +
//                    "\t\t\t\t\t<ReturnMsg>成功！</ReturnMsg>\n" +
//                    "\t\t\t\t\t<AcNo>13618800286303</AcNo>\n" +
//                    "\t\t\t\t\t<Currency>CNY</Currency>\n" +
//                    "\t\t\t\t\t<Amount>6.66</Amount>\n" +
//                    "\t\t\t\t\t<PayeeAcNo>04618800081038</PayeeAcNo>\n" +
//                    "\t\t\t\t\t<TransResultCode>0</TransResultCode>\n" +
//                    "\t\t\t\t\t<TransResult>交易成功</TransResult>\n" +
//                    "\t\t\t\t</Map>\n" +
//                    "\t\t</List>\n" +
//                    "\t</Body>\n" +
//                    "</Message>\n";
//            String[] bankResult = new String[]{"", s};

            if (bankResult[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader xmlSbReader = loadBankRespXmlReader(bankResult[1], tmpSbMsg);
                if (xmlSbReader != null) {
                    String respCode = xmlSbReader.getFirstText("/Message/Head/IBSReturnCode");
                    String respInfo = xmlSbReader.getFirstText("/Message/Head/IBSReturnMsg");
                    if ("000000".equals(respCode)) {//交易成功
                        String code = xmlSbReader.getFirstText("/Message/Body/List/Map/ReturnCode");
                        String info = xmlSbReader.getFirstText("/Message/Body/List/Map/ReturnMsg");
                        p_req1944.payAct = xmlSbReader.getFirstText("/Message/Body/List/Map/AcNo");
//                        if ("000000".equals(code) && (p_req1944.payAct).equals(str)) {
//                        detail.transState =p_req1944.reqHeader.commandCode+code;//状态
                        detail.respCode = "0";
                        detail.respInfo = xmlSbReader.getFirstText("/Message/Body/List/Map/TransResult");//交易结果
                        detail.reqSeqID = p_req1944.askNumber;
                        detail.transAmt = xmlSbReader.getFirstText("/Message/Body/List/Map/Amount");//金额

//                        detail.transState = xmlSbReader.getFirstText("/Message/Body/List/Map/Status");//状态
//                        detail.transState = xmlSbReader.getFirstText("/Message/Body/List/Map/Currency");//币种代码
//                        detail.transState = xmlSbReader.getFirstText("/Message/Body/List/Map/PayeeAcNo");//对方帐号

                        String str = xmlSbReader.getFirstText("/Message/Body/List/Map/TransResultCode");//被查询的交易之结果代码
//
                        if (code != null && code.equals("000000")) {
                            detail.transState = code + "+" + str;
                        } else {
                            detail.respCode = "-1";
                            detail.transState = code + "+" + str;
                        }
                        detail.payInfoCode = detail.transState;
//                        }
                    } else if (respCode != null && "999999".equals(respCode)) {// 如果是ct通讯机校验错误，或者通讯失败
                        retAtsSingle.writeRespCode("-1");
                        retAtsSingle.writeRespInfo(respInfo);
                    } else {
                        detail.respCode = "-1";
                        detail.respInfo = respInfo;
                    }
                } else {
                    detail.respCode = "-1";
                    detail.respInfo = tmpSbMsg.toString();
                }
            } else {
                detail.respCode = "-1";
                detail.respInfo = bankResult[1];
            }


        } catch (Exception ex) {
            detail.respCode = "-1";
            detail.respInfo = ex.getMessage();
            ex.printStackTrace();
        }

        retAtsSingle.writeRetDetail(detail);
        return retAtsSingle;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}
